﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace CZ.PAEZ.SaleManager.ListPlugIns
{
    [Description("发票列表")]
    [HotUpdate]
    public class InvoiceList : AbstractListPlugIn
    {
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            switch (e.BarItemKey.ToUpperInvariant())
            {
                case "TBGTCREATEIV": // tbGTCreateIV 金税发票开具
                    //Act_ABIC_CheckInvoice();
                    break;
                case "TBINVOICEADJUST": //tbInvoiceAdjust 提货联发票号调整
                    Act_ABIC_AdjustInvoices();
                    break;
            }
        }

        /// <summary>
        /// 调整断号的发票号
        /// </summary>
        private void Act_ABIC_AdjustInvoices()
        {
            var fids = this.ListView.SelectedRowsInfo
                .DistinctBy(i => i.PrimaryKeyValue)
                .Select(i => i.PrimaryKeyValue)
                .ToArray();
            if (fids.Length <= 0)
            {
                this.View.ShowErrMessage("请先选中单据！");
                return;
            }
            string sql = string.Format(@"
select s.FID, so.FIVNUMBER 
from T_IV_SALESIC s
inner join T_IV_SALESIC_O so on so.FID=s.FID
where s.FID in ({0}) 
and isnull(so.FIVNUMBER, '')<>'' and s.FINVOICENO<>so.FIVNUMBER
", string.Join(",", fids));
            var forms = DBUtils.ExecuteDynamicObject(Context, sql)
                .Select(i => new {
                    FID = i["FID"].ToString(),
                    FIvNumber = i["FIVNUMBER"].ToString()
                })
                .ToArray();
            if (forms.Length <= 0)
            {
                this.View.ShowErrMessage("没有选中有效的单据！");
                return;
            }
            var ids = string.Join(",", forms.Select(i => i.FID).ToArray());
            // 获取提货联ID
            sql = string.Format(@"
select distinct l.FID, sc.FIVNUMBER from PAEZ_t_Lading l
inner join PAEZ_t_LadingEntry le on le.FID=l.FID
inner join T_BD_Customer c on c.FCustId=l.FCustomerID
inner join T_BD_Customer_L cl on cl.FCustId=c.FCustId
inner join t_AR_receivableEntry_LK relk on relk.FSId=le.FEntryId and relk.FSTableName='PAEZ_t_LadingEntry'
inner join t_AR_receivableEntry re on re.FEntryId=relk.FEntryId
inner join t_AR_receivable r on r.FID=re.FID
inner join T_IV_SALESICENTRY_LK scelk on scelk.FSId=relk.FEntryId and scelk.FSTableName='t_AR_receivableEntry'
inner join T_IV_SALESICENTRY sce on sce.FEntryId=scelk.FEntryId
inner join T_IV_SALESIC_O sc on sc.FID=sce.FID
where sc.FID in ({0})", ids);
            var Ladings = DBUtils.ExecuteDynamicObject(Context, sql)
                .Select(i => new { 
                    FID = i["FID"].ToString(),
                    FIvNumber = i["FIVNUMBER"].ToString()
                }).ToArray();
            // 获取应收单ID
            sql = string.Format(@"
select distinct r.FID, sc.FIVNUMBER
from t_AR_receivable r
inner join t_AR_receivableEntry re on re.FID=r.FID
inner join T_IV_SALESICENTRY_LK scelk on scelk.FSId=re.FEntryId and scelk.FSTableName='t_AR_receivableEntry'
inner join T_IV_SALESICENTRY sce on sce.FEntryId=scelk.FEntryId
inner join T_IV_SALESIC_O sc on sc.FID=sce.FID
where sc.FID in ({0})", ids);
            var Rcvs = DBUtils.ExecuteDynamicObject(Context, sql)
                .Select(i => new {
                    FID = i["FID"].ToString(),
                    FIvNumber = i["FIVNUMBER"].ToString()
                })
                .ToArray();
            sql = "";
            foreach(var form in forms)
            {
                sql += $"update T_IV_SALESIC set FINVOICENO='{form.FIvNumber}' where FID={form.FID};";
            }
            foreach (var form in Ladings)
            {
                sql += $"update PAEZ_t_Lading set FInvoice='{form.FIvNumber}' where FID={form.FID};";
            }
            foreach(var form in Rcvs)
            {
                sql += $"update t_AR_receivable set FBillNo='{form.FIvNumber}' where FID={form.FID};";
            }
            // this.View.ShowErrMessage(sql);
            DBUtils.Execute(Context, sql);
            this.View.Refresh();
            this.View.ShowMessage($"修改成功{Ladings.Length}条数据");
        }

        /// <summary>
        /// 检查开具的发票号和由提货联携带的发票号是否相同
        /// </summary>
        private void Act_ABIC_CheckInvoice()
        {
            var ids = this.ListView.SelectedRowsInfo
                .DistinctBy(i => i.PrimaryKeyValue)
                .Select(i => i.PrimaryKeyValue)
                .ToArray();
            if (ids.Length <= 0) return;
            string sql = $"select FBillNo from T_IV_SALESIC where FBillNo<>FINVOICENO and FID in ({string.Join(",", ids)})";
            var items = DBUtils.ExecuteDynamicObject(Context, sql);
            if(items.Count > 0)
            {
                var nos = items.Select(i => i["FBillNo"].ToString()).ToArray();
                string msg = $"以下单据编号与开具的发票号不同，请检查发票号是否断号：\n{string.Join(",", nos)}";
                this.View.ShowMessage(msg);
            }
        }


    }
}
